import { defineStore } from "pinia";
import { decrypto, encrypto } from "@/utils/crypto";
import API from "@/service/api/login";
import { request } from "@/service/request";
import CryptoJS from "crypto-js";
import router from "@/router";
import { someFieldStore } from "@/stores/somefield";
import { getUrlParamValue } from "@/utils/getUrlParams";

// 动态导入密钥
const keys = await import("@/config/keys");
const { key_part1, key_part2 } = keys.default;

export const useStore = defineStore("user", {
  state: (): any => {
    return {
      userInf: {},
      state: false,
      token: {
        user:{}
      },
    };
  },
  actions: {
    //token
    async getToken(Index: number) {
      try {
        //手机号登录对应的code
        let index = 0;
        if (Index) {
          index = Index;
        }
        const extension = JSON.stringify({
          code: this.userInf.user_list[index].verify_code,
        });
        const mSomeField = someFieldStore();
        const urlGameId = getUrlParamValue("game_id", mSomeField.clientfields);
        const gameId = urlGameId !== null && !isNaN(Number(urlGameId))? Number(urlGameId): 0;  //如果有给game_id参数就用game_id，没有就用0
        const app_key = key_part1 + "#" + gameId + "#" + key_part2;
        const sign = CryptoJS.MD5(
          `appID=${gameId}channelID=1extension=${extension}${app_key}`
        ).toString();

        const requestObj = {
          agent_id: "100",
          site_id: "1001",
          channel_id: 1,
          bundle_id: "",
          extension: extension,
          os: "pc",
          sign: sign,
        };
        const { data } = await request.post<any>(API.getToken, requestObj);
        this.token = data;

        //登陆成功回跳
        if (router.currentRoute.value.query.redirect) {
          router.push(`${router.currentRoute.value.query.redirect}`);
        } else {
          router.push("/");
        }
      } catch (error) {
        // token获取失败，重置state参数，不保存
        this.userInf = {};
        this.token = { user: {} };
        this.state = false;
        console.error('Token获取失败:', error);
        throw error; // 重新抛出错误，让调用方处理
      }
    },
    updateUser(data: any, type: string) {
      if (this.state == true) {
        // 如果用户已登录，且再次登录，则清除之前的用户信息
        this.userInf = {};
        this.token = "";
        this.state = false;
      }

      this.userInf = data;
      this.state = true;
      if (type == "account" || data.user_list.length == 1) {
        this.getToken();
      }
    },
  },
  persist: {
    key: "user",
    serializer: {
      deserialize: decrypto,
      serialize: encrypto,
    },
  },
});
